﻿using SqlSugar;

namespace Framework.Core.Cache
{
	/// <summary>
	/// SqlSugar二级缓存
	/// </summary>
	public class SqlSugarCache : ICacheService
	{
		/// <summary>
		/// SqlSugar二级缓存
		/// </summary>
		const string SqlSugar = "sys_sqlSugar:";

		/// <summary>
		/// 系统缓存服务
		/// </summary>
		private static readonly CacheHelp _cache = App.GetService<CacheHelp>();

		public void Add<V>(string key, V value)
		{
			//CacheHelp _cache = App.GetRequiredService<CacheHelp>();
			_cache.Set($"{SqlSugar}{key}", value);
		}

		public void Add<V>(string key, V value, int cacheDurationInSeconds)
		{
			//CacheHelp _cache = App.GetRequiredService<CacheHelp>();
			_cache.Set($"{SqlSugar}{key}", value, TimeSpan.FromSeconds(cacheDurationInSeconds));
		}

		public bool ContainsKey<V>(string key)
		{
			//CacheHelp _cache = App.GetRequiredService<CacheHelp>();
			return _cache.ExistKey($"{SqlSugar}{key}");
		}

		public V Get<V>(string key)
		{
			//CacheHelp _cache = App.GetRequiredService<CacheHelp>();
			return _cache.Get<V>($"{SqlSugar}{key}");
		}

		public IEnumerable<string> GetAllKey<V>()
		{
			//CacheHelp _cache = App.GetRequiredService<CacheHelp>();
			if (_cache == null) return null;
			
			return _cache.GetKeysByPrefixKey(SqlSugar);
		}

		public V GetOrCreate<V>(string key, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
		{
			//CacheHelp _cache = App.GetRequiredService<CacheHelp>();
			return _cache.GetOrAdd<V>($"{SqlSugar}{key}", (cacheKey) =>
			{
				return create();
			}, cacheDurationInSeconds);
		}

		public void Remove<V>(string key)
		{
			//CacheHelp _cache = App.GetRequiredService<CacheHelp>();
			_cache.Remove(key); // SqlSugar调用Remove方法时，key中已包含了SqlSugar前缀
		}
	}
}
